import logging
import traceback

import requests
import json
from retrying import retry
from conf.config import dingding_robot_url
logger = logging.getLogger('log')


class DingDingRoBot:
    # 发送上新消息
    @retry(stop_max_attempt_number=5)
    def send_message(self, content):
        try:
            msg = {
                "text": {
                    "content": f"monitor\n{content}"
                },
                "msgtype": "text"
            }
            res = requests.post(url=dingding_robot_url, headers={"Content-Type": "application/json"}, json=msg,
                                timeout=15, verify=False)
            if res.status_code == 200:
                sends = json.loads(res.text)
                if sends["errcode"] == 0:
                    logger.info(f"发送消息成功")
                    return True
                else:
                    logger.info(f"发送消息失败：{res.text}")
        except Exception:
            logger.info(f"发送消息失败：{traceback.format_exc()}")
            raise Exception
        return False
